<?php

namespace App\Admin\Controllers;

use App\Models\Agent;
use App\Http\Controllers\Controller;
use App\Models\Staff;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;

class AgentController extends Controller
{
	use HasResourceActions;

	const TITLE = '经销商管理';

	public function index(Content $content)
	{
		return $content
			->header(self::TITLE)
			->description(' ')
			->body($this->grid());
	}

	public function show($id, Content $content)
	{
		return $content
			->header(self::TITLE)
			->description(' ')
			->body($this->detail($id));
	}

	public function edit($id, Content $content)
	{
		return $content
			->header(self::TITLE)
			->description(' ')
			->body($this->form($id)->edit($id));
	}

	public function create(Content $content)
	{
		return $content
			->header(self::TITLE)
			->description(' ')
			->body($this->form());
	}

	protected function grid()
	{
		$grid = new Grid(new Agent);

		$grid->disableExport();
		$grid->disableFilter();

		$grid->id('ID');
		$grid->name('名称');
		$grid->admin_name('管理员姓名')->display(function () {
			return $this->admin->name;
		});
		$grid->admin_mobile('管理员手机')->display(function () {
			return $this->admin->mobile;
		});
		$grid->created_at('创建时间');

		return $grid;
	}

	protected function detail($id)
	{
		$show  = new Show(Agent::findOrFail($id));

		$show->name('名称');
		$show->admin_name('管理员姓名')->as(function () {
			return $this->admin->name;
		});;
		$show->admin_mobile('管理员手机')->as(function () {
			return $this->admin->mobile;
		});;
		$show->id_number('法人身份证');
		$show->charter('营业执照')->image();
		$show->created_at('创建时间');
		$show->updated_at('更新时间');

		return $show;
	}

	protected function form($id = 0)
	{
		$form = new Form(new Agent);
		$form->disableViewCheck();
		$form->disableEditingCheck();
		if ($id) {
			$form->disableCreatingCheck();
		}
		$admins = Staff::query()->where('genre', Staff::ADMIN)->pluck('name as text', 'id');

		$form->text('name', '名称')->rules('required|string|max:16');
		$form->text('id_number', '法人身份证号')->rules('required|string|max:18');
		$form->image('charter', '营业执照')->rules('required');
		$form->radio('admin_id', '管理员')->options($admins)->rules('required');

		return $form;
	}
}
